package ve.basura.entrada.form;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.springframework.beans.factory.annotation.Autowired;

import com.aseo.model.entity.hibernate.Chofer;
import com.aseo.model.entity.hibernate.Vehiculo;

import ve.basura.entrada.bdl.EntradaSalidaBDL;
import ve.basura.entrada.listener.AddListener;
import ve.basura.entrada.main.EntradaMain;
import ve.basura.entrada.util.EntradaSalidaUtil;


public class SeleccionChoferDialog {
	
	private Shell shell ; 
	private Table table;
	private Chofer result;
	private List<Chofer> choferes;
	
	private MessageBox dialog;
	
	AddListener addListener;
	private static final String[] columnNames = {"Codigo Chofer",
		 										 "Nombre Chofer" };
	
	private int lastSortColumn= -1;
	
	EntradaSalidaUtil entradaSalidaUtil;
	
	@Autowired
	EntradaSalidaBDL entradaSalidaBDL;
	
	public SeleccionChoferDialog(){
		
	}
	
	public  SeleccionChoferDialog(Shell shell , EntradaSalidaUtil entradaSalidaUtil){
		this.entradaSalidaUtil= entradaSalidaUtil;
		this.shell=shell;
		generateGUI();			
	}
	
	private void generateGUI(){
		
		//inicializacion del dialog
		dialog= new MessageBox (shell, SWT.OK|SWT.ICON_WARNING);

		GridLayout layout = new GridLayout(1,true);
		
		//FillLayout layout = new FillLayout();
		shell.setLayout(layout);
		shell.setText(entradaSalidaUtil.getProperty("seleccionChoferDialog.tituloLabel"));
		shell.setSize(570,450);
		shell.addShellListener(new ShellAdapter(){
			public void shellClosed(ShellEvent e) {
				// don't dispose of the shell, just hide it for later use
				e.doit = false;
				shell.setVisible(false);
			}
		});
		
		    table = new Table(shell, SWT.SINGLE | SWT.BORDER | SWT.FULL_SELECTION | SWT.V_SCROLL);
		    table.setHeaderVisible(true);	
		    //table.setSize(300, 500);
			table.addSelectionListener(new SelectionAdapter() {
				public void widgetSelected(SelectionEvent e) {
					Chofer chofer = choferes.get(table.getSelectionIndex());
					setResult(chofer);
				}
			});
			
			for(int i = 0; i < columnNames.length; i++) {
				TableColumn column = new TableColumn(table, SWT.FILL);
				
				column.setText(columnNames[i]);
				column.setWidth(260);
				
				final int columnIndex = i;
				column.addSelectionListener(new SelectionAdapter() {		
					public void widgetSelected(SelectionEvent e) {
						sort(columnIndex);
					}
				});
			}
			
			table.getColumn(0).setImage(entradaSalidaUtil.getImagesMap().get("codeImage"));
			table.getColumn(1).setImage(entradaSalidaUtil.getImagesMap().get("userImage"));
			
			GridData gridData = new GridData();
			gridData.grabExcessHorizontalSpace= true;
			gridData.grabExcessVerticalSpace = true;
			gridData.horizontalAlignment=SWT.FILL;
			gridData.verticalAlignment=SWT.FILL;
			table.setLayoutData(gridData);
			
			Button aceptarButton = new Button(shell,SWT.PUSH);
			aceptarButton.setText(entradaSalidaUtil.getProperty("seleccionChoferDialog.aceptarButtonLabel"));
			aceptarButton.setImage(entradaSalidaUtil.getImagesMap().get("acceptImage"));
			aceptarButton.addSelectionListener(new SelectionAdapter() {
				public void widgetSelected(SelectionEvent event) {
					
					TableItem[] items = table.getSelection();

					if (items.length > 0){
						shell.close();
						shell.dispose();
					}else{
						alert("seleccionChoferDialog.debeSeleccionarMessage");	
					}
					 
				}
			});
			gridData = new GridData(SWT.FILL);
			gridData.grabExcessHorizontalSpace= true;
			gridData.horizontalAlignment = SWT.CENTER;
			gridData.verticalAlignment = SWT.FILL;
			aceptarButton.setLayoutData(gridData);
			
		/*	//prueba 
			String [] data = new String[2];
			data[0] = "23232323";
			data[1] = "Pedro Perez";
			TableItem item = new TableItem(table, SWT.NONE);
			item.setText(data);
			*/
	}
	
	
	private void sort(int column) {
		if(table.getItemCount() <= 1) return;

		TableItem[] items = table.getItems();
		String[][] data = new String[items.length][table.getColumnCount()];
		for(int i = 0; i < items.length; i++) {
			for(int j = 0; j < table.getColumnCount(); j++) {
				data[i][j] = items[i].getText(j);
			}
		}
		
		Arrays.sort(data, new RowComparator(column));
		
		if (lastSortColumn != column) {
			table.setSortColumn(table.getColumn(column));
			table.setSortDirection(SWT.DOWN);
			for (int i = 0; i < data.length; i++) {
				items[i].setText(data[i]);
			}
			lastSortColumn = column;
		} else {
			// reverse order if the current column is selected again
			table.setSortDirection(SWT.UP);
			int j = data.length -1;
			for (int i = 0; i < data.length; i++) {
				items[i].setText(data[j--]);
			}
			lastSortColumn = -1;
		}
		
	}
	
	/**
	 * To compare entries (rows) by the given column
	 */
	@SuppressWarnings("unchecked")
	private class RowComparator implements Comparator {
		
		private int column;
		
		/**
		 * Constructs a RowComparator given the column index
		 * @param col The index (starting at zero) of the column
		 */
		public RowComparator(int col) {
			column = col;
		}
		
		/**
		 * Compares two rows (type String[]) using the specified
		 * column entry.
		 * @param obj1 First row to compare
		 * @param obj2 Second row to compare
		 * @return negative if obj1 less than obj2, positive if
		 * 			obj1 greater than obj2, and zero if equal.
		 */
		public int compare(Object obj1, Object obj2) {
			String[] row1 = (String[])obj1;
			String[] row2 = (String[])obj2;
			
			return row1[column].compareTo(row2[column]);
		}
	}
	
	

	/**
	 * @return the addListener
	 */
	public AddListener getAddListener() {
		return addListener;
	}

	/**
	 * @param addListener the addListener to set
	 */
	public void setAddListener(AddListener addListener) {
		this.addListener = addListener;
	}
	

	/**
	 * @return the result
	 */
	public Chofer getResult() {
		return result;
	}

	/**
	 * @param result the result to set
	 */
	public void setResult(Chofer result) {
		this.result = result;
	}
	
	public Chofer open() {

			shell.open();
			
			Display display = shell.getDisplay();
			while(!shell.isDisposed()){
				if(!display.readAndDispatch())
					display.sleep();
			}
		
		return getResult();//getChoferCodigo();
	}
	
	public boolean populateList(){
		
	if(table != null && table.getItemCount()>0)return true;
		
		choferes = entradaSalidaBDL.getChoferes();
		
		for(Chofer chofer: choferes){
			String [] data = new String[2];
			data[0] = chofer.getChoferId().toString();
			data[1] = chofer.getApellidos()+", "+chofer.getNombres();
			TableItem item = new TableItem(table, SWT.NONE);
			item.setText(data);
		}
		
		return true; 
	}
	
	public void alert(String propertyString){
		dialog.setMessage (entradaSalidaUtil.getProperty(propertyString));
		dialog.setText(entradaSalidaUtil.getProperty("seleccionChoferDialog.informacionLabel"));
		dialog.open();
	};

	/**
	 * @param entradaSalidaBDL the entradaSalidaBDL to set
	 */
	public void setEntradaSalidaBDL(EntradaSalidaBDL entradaSalidaBDL) {
		this.entradaSalidaBDL = entradaSalidaBDL;
	}

}
